import { Effect, Reducer } from 'umi';

import { query,queryCurrent } from '@/services/new';

export interface CurrentNew {
  avatar?: string;
  name?: string;
  title?: string;
  group?: string;
  signature?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  userid?: string;
  unreadCount?: number;
}

export interface NewModelState {
  currentNew?: CurrentNew;
}

export interface NewModelType {
  namespace: 'new';
  state: NewModelState;
  effects: {
    fetch: Effect;
    fetchCurrent: Effect;
  };
  reducers: {
    saveCurrentNew: Reducer<NewModelType>;
    changeNotifyCount: Reducer<NewModelType>;
  };
}

const NewModel: NewModelType = {
  namespace: 'new',

  state: {
    currentNew: {},
  },

  effects: {
    *fetch(_, { call, put }) {
      const response = yield call(query);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *fetchCurrent(_, { call, put }) {
      const response = yield call(queryCurrent);
      yield put({
        type: 'saveCurrentNew',
        payload: response,
      });
    },
  },

  reducers: {
    saveCurrentNew(state, action) {
      return {
        ...state,
        currentNew: action.payload || {},
      };
    },
    changeNotifyCount(
      state = {
        currentNew: {},
      },
      action,
    ) {
      return {
        ...state,
        currentNew: {
          ...state.currentNew,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};

export default NewModel;
